<template>
    <div class="ueditor_container">
        <vue-ueditor-wrap ref="UeditorWrap" v-model="ueditorValue" :config="config" @ready="ready" />
    </div>
</template>

<script>
import { mapState } from "vuex";
import VueUeditorWrap from 'vue-ueditor-wrap'
import constants from "@common/api/constants";

export default {
    name: "UEditor",
    components: { VueUeditorWrap },
    props: {
        bizType: String,
        bizTable: String,
        bizSid: String,
        bizFieldTag: String,
        wordCount: {
            type: Boolean,
            default: true,
        },
        maximumWords: Number,
        value: String,
    },
    data() {
        return {
            config: {
                UEDITOR_HOME_URL: './static/plugins/ueditor/',
            },
            editorInstance: undefined,
            ueditorValue: this.value,
        };
    },
    computed: {
        ...mapState(['accessToken']),
        serverUrl() {
            let url = window.configs.requestPrefix + constants.Anon_UeditorConfig;
            let params = [];
            if (this.accessToken && this.accessToken.token) {
                params.push(`token=${this.accessToken.token}`);
            }
            let account = this.$utils.getAccountSetSid();
            if (this.$utils.isNotEmpty(account)) {
                params.push(`account_set_sid=${account}`);
            }
            if (this.$utils.isNotEmpty(this.bizType)) {
                params.push(`biz_type=${this.bizType}`);
            }
            if (this.$utils.isNotEmpty(this.bizTable)) {
                params.push(`associate_biz_table=${this.bizTable}`);
            }
            if (this.$utils.isNotEmpty(this.bizSid)) {
                params.push(`associate_biz_sid=${this.bizSid}`);
            }
            if (this.$utils.isNotEmpty(this.bizFieldTag)) {
                params.push(`associate_biz_field_tag=${this.bizFieldTag}`);
            }
            if (this.$utils.isNotEmptyList(params)) {
                url = `${url}?${params.join('&')}`;
            }
            return url;
        },
    },
    watch: {
        value() {
            this.ueditorValue = this.value;
        },
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            let _this = this;
            _this.ueditorValue = _this.value;
            _this.config = $.extend({}, _this.config, {
                serverUrl: _this.serverUrl,
                wordCount: _this.wordCount,
                maximumWords: _this.maximumWords,
            });
        },
        ready(editorInstance) {
            this.editorInstance = editorInstance;
        },
        getContent() {
            if (this.editorInstance) {
                return this.editorInstance.getContent();
            }
            return undefined;
        },
    },
}
</script>

<style scoped lang="less" rel="stylesheet/less">
.ueditor_container {
    width: 100%;
    height: 100%;
    overflow: auto;
}
</style>
